<script setup>
import { onMounted, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { addApi, queryPageApi, queryByIdApi, updateApi, deleteApi, queryAllApi } from "@/api/role";
// 查询参数
const queryParams = ref({
  name: "",
  label: "",
  page: 1,
  pageSize: 10,
});

// 表格数据
const roleList = ref([]);
const total = ref(0);

// 搜索
const search = async () => {
  const result = await queryPageApi(queryParams.value);
  if (result.code == 1) {
    roleList.value = result.data.rows;
    total.value = result.data.total;
  }
};

// 清空
const clear = () => {
  queryParams.value = { name: "", label: "", page: 1, pageSize: 10 };
  search();
};

// 分页大小改变
const handleSizeChange = () => {
  search();
};

// 页码改变
const handleCurrentChange = () => {
  search();
};
//页面加载完毕后查询
onMounted(() => {
  search();
});

// 对话框
const formTitle = ref("");
const dialogFormVisible = ref(false);
const formLabelWidth = "100px";
const role = ref({
  id: undefined,
  name: "",
  label: "",
  status: 1,
  remark: "",
});
// 添加角色
const handleAdd = () => {
  dialogFormVisible.value = true;
  formTitle.value = "新增角色";
  role.value = { id: undefined, name: "", label: "", status: 1, remark: "" };
  if (roleFormRef.value) {
    roleFormRef.value.resetFields();
  }
};

// 远程唯一性校验
const validateNameUnique = async (rule, value, callback) => {
  if (!value) return callback();
  const res = await queryAllApi();
  if (res.code !== 1) return callback(new Error(res.msg || "校验失败"));
  const exists = (res.data || []).some((r) => r.name === value && r.id !== role.value.id);
  return exists ? callback(new Error("角色名称已存在")) : callback();
};
const validateLabelUnique = async (rule, value, callback) => {
  if (!value) return callback();
  const res = await queryAllApi();
  if (res.code !== 1) return callback(new Error(res.msg || "校验失败"));
  const exists = (res.data || []).some((r) => r.label === value && r.id !== role.value.id);
  return exists ? callback(new Error("角色标识已存在")) : callback();
};

// 表单校验规则
const roleFormRef = ref(null);
const rules = ref({
  name: [
    { required: true, message: "角色名称为必填项", trigger: "blur" },
    { min: 2, max: 10, message: "角色名称应该在2-10位之间", trigger: "blur" },
    { validator: validateNameUnique, trigger: "blur" },
  ],
  label: [
    { required: true, message: "角色标识为必填项", trigger: "blur" },
    { min: 2, max: 20, message: "角色标识应该在2-20位之间", trigger: "blur" },
    { pattern: /^[a-zA-Z][a-zA-Z0-9_]{1,19}$/, message: "以字母开头, 由字母数字下划线组成", trigger: "blur" },
    { validator: validateLabelUnique, trigger: "blur" },
  ],
  remark: [{ max: 50, message: "备注不超过50字", trigger: "blur" }],
});
// 保存角色
const save = async () => {
  roleFormRef.value.validate(async (valid) => {
    if (!valid) return;
    let result;
    if (role.value.id) {
      result = await updateApi(role.value);
    } else {
      result = await addApi(role.value);
    }
    if (result.code == 1) {
      ElMessage.success("保存成功");
      dialogFormVisible.value = false;
      search();
    } else {
      ElMessage.error(result.msg || "保存失败");
    }
  });
};

const handleEdit = async (id) => {
  const result = await queryByIdApi(id);
  if (result.code == 1) {
    dialogFormVisible.value = true;
    formTitle.value = "修改角色";
    role.value = result.data;
    if (role.value.status === undefined || role.value.status === null) {
      role.value.status = 1;
    }
    if (roleFormRef.value) {
      roleFormRef.value.clearValidate();
    }
  } else {
    ElMessage.error(result.msg);
  }
};
//删除角色
const handleDelete = (id, name) => {
  ElMessageBox.confirm("您确认删除该角色吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const result = await deleteApi(id);
      if (result.code == 1) {
        ElMessage({ type: "success", message: "删除成功" });
        search();
      } else {
        ElMessage({ type: "error", message: result.msg || "删除失败" });
      }
    })
    .catch(() => {});
};
</script>

<template>
  <div class="department">
    <!-- 搜索区域 -->
    <el-form :inline="true" :model="queryParams" ref="queryForm" class="search-form">
      <el-form-item label="角色名称">
        <el-input v-model="queryParams.name" placeholder="请输入角色名称" />
      </el-form-item>
      <el-form-item label="角色标识">
        <el-input v-model="queryParams.label" placeholder="请输入角色标识" />
      </el-form-item>

      <el-form-item class="search-buttons">
        <el-button type="primary" @click="search"><el-icon><Search /></el-icon>搜索</el-button>
        <el-button @click="clear"><el-icon><Refresh /></el-icon>清空</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <div class="operation-area">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>添加角色
      </el-button>
    </div>

    <!-- 表格区域 -->
    <el-table :data="roleList" style="width: 100%" border>
      <el-table-column type="index" label="序号" width="100" align="center" />
      <el-table-column prop="name" label="角色名称" width="350" align="center" />
      <el-table-column prop="label" label="角色标识" width="350" align="center" />
      <el-table-column prop="updateTime" label="最后修改时间" width="350" align="center" />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" link @click="handleEdit(scope.row.id)">
            <el-icon><Edit /></el-icon>修改
          </el-button>
          <el-button type="danger" link @click="handleDelete(scope.row.id, scope.row.name)">
            <el-icon><Delete /></el-icon>删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 30, 40, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/修改 角色 对话框 -->
    <el-dialog v-model="dialogFormVisible" :title="formTitle" width="450">
      <el-form :model="role" :rules="rules" ref="roleFormRef">
        <el-form-item label="角色名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="role.name" autocomplete="off" placeholder="请输入角色名称" />
        </el-form-item>

        <el-form-item label="角色标识" :label-width="formLabelWidth" prop="label">
          <el-input v-model="role.label" autocomplete="off" placeholder="请输入角色标识" />
        </el-form-item>

        <el-form-item label="备注说明" :label-width="formLabelWidth" prop="remark">
          <el-input v-model="role.remark" type="textarea" :rows="3" maxlength="50" show-word-limit placeholder="请输入角色的备注信息" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="save">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.department {
  padding: 20px;
  background-color: #fff;
  min-height: 100%;
  border-radius: 8px;
}

.operation-area {
  margin: 20px 0;
}

.search-form {
  display: flex;
  align-items: center;
}

.search-form :deep(.el-form-item) {
  margin-right: 20px;
  min-width: 280px;
}

.search-buttons {
  margin-left: auto !important;
  min-width: auto !important;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.divider {
  height: 0.5px;
  background-color: #dcdfe6;
  margin: 10px 0;
  width: 100%;
}

:deep(.dept-dialog .el-dialog__body) {
  padding-top: 30px;
}

.dept-form {
  width: 80%;
  margin: 0 auto;
}

:deep(.el-button .el-icon) {
  margin-right: 4px;
}
</style>
